package jianzhi_offer;

public class _52_表示数值的字符串 {
    public static void main(String[] args) {
        _52_表示数值的字符串 test = new _52_表示数值的字符串();
        System.out.println(test.isNumeric("123.45e+6".toCharArray()));
        System.out.println(test.isNumeric("+100".toCharArray()));
        System.out.println(test.isNumeric("5e2".toCharArray()));
        System.out.println(test.isNumeric("-123".toCharArray()));
        System.out.println(test.isNumeric("3.1416".toCharArray()));
        System.out.println(test.isNumeric("-1E-16".toCharArray()));
        System.out.println(test.isNumeric("12e".toCharArray()));
        System.out.println(test.isNumeric("1a3.14".toCharArray()));
        System.out.println(test.isNumeric("1.2.3".toCharArray()));
        System.out.println(test.isNumeric("+-5".toCharArray()));
        System.out.println(test.isNumeric("12e+4.3".toCharArray()));


    }
    //+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。

    public boolean isNumeric(char[] str) {
        if(str == null || str.length == 0) return false;
        int index = hasSpecil(str);
        if(index != -1){
            return isValid(str,0,index-1,false)&&isValid(str,index+1,str.length-1,true);
        }
        return isValid(str,0,str.length,false);
    }

    public int hasSpecil(char[] str){
        for(int i=0;i<str.length;++i){
            if( str[i] == 'e' || str[i] == 'E'){
                return i;
            }
        }
        return -1;
    }

    //flag = true 表示是已经小数
    public boolean  isValid(char[] str,int left,int right,boolean flag){
        if(left > right) return false;
        if(str[left] == '+' || str[left] == '-'){
            //if(flag) return false;
            ++left;
            if(left > right) return false;
        }
        while(left != right){
            if(str[left] == '.'){
                if(flag) return false;
                flag = true;
                ++left;
                continue;
            }
            if(! (str[left] <= '9' && str[left] >= '0')) {
                return false;
            }
            ++left;
        }
        return true;
    }
}
